/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sourcecodeexecutor;

import executing.*;
import executingimpl.buildservice.BuildService;
import executingimpl.executeservice.ExecuteService;
import executor.ExecutingException;
import executor.ExecutionItem;
import executor.ExecutionResult;
import executor.SC_ExecutorPOA;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.omg.CORBA.ORB;

/**
 *
 * @author ryuju
 */
public class SourceCodeExecutor extends SC_ExecutorPOA {

    private ORB orb;
    private static Logger logger = Logger.getLogger(SourceCodeExecutor.class.getName());
    
    
    public void setORB(ORB orb)
    {
        this.orb = orb;
    }
    
    
    @Override
    public ExecutionResult execute(ExecutionItem execItem) throws ExecutingException {

        logger.log(Level.INFO, "Call execute");

        IBuildService buildSvc = new BuildService();
        IExecuteService execSvc = new ExecuteService();
        IBuilder builder = null;
        IExecutor executor = null;
        ExecutionResult execResult = ExecutionResultFactory.getEmptyExecutionResult();
        TempBuildDirectory tempDir = null;
        try {
            // build 
            builder = buildSvc.getTestBuilder(execItem);
            tempDir = TempBuildDirFactory.getTempBuildDir();
            
            if(builder.build(execItem, tempDir.getAbsolutePath()))
            {
                logger.log(Level.INFO, "Build sucess");
            }
            else
            {
                logger.log(Level.INFO, "Build fail");
            }
            
            logger.log(Level.INFO, "Execution start...");
            executor = execSvc.getExecutor(execItem);
            if (null != executor) {
                execResult = executor.execute(execItem, tempDir.getAbsolutePath());
            }
            
            logger.log(Level.INFO, "execute success");
             
        } 
        catch(ExecutingException ee)
        {
            logger.log(Level.SEVERE, ee.msg);
            throw ee;
        }
        catch (Exception e) {
            
            Logger.getLogger(SourceCodeExecutor.class.getName()).log(Level.SEVERE, e.getMessage());
            ExecutingException ex = new ExecutingException();
            ex.msg = e.getMessage();
            throw ex;
        }
        finally
        {
            try
            {
                tempDir.dispose();
            }
            catch(Exception e)
            {
                // not thing..
            }
        }
        return execResult;
    }
}
